package com.yixiu.study.juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @CalssName T01_ReenTrantLock
 * @Description
 * @Author yixiu
 * @Date 2021/6/24 9:46
 * @Verison num1.0
 **/
public class T01_ReenTrantLock {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            try {
                lock.lock();
                System.out.println("t1 start");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
                System.out.println("t1 end");
            } catch (InterruptedException e){
                e.printStackTrace();
                System.out.println("Interrupted");
            } finally {
                lock.unlock();
            }
        });

        t1.start();

        Thread t2 = new Thread(() -> {
            try {
//                lock.lock();

                //可以对interrupt()方法做出响应
                lock.lockInterruptibly();

                System.out.println("t2 start");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("t2 end");
            } catch (InterruptedException e){
                e.printStackTrace();
                System.out.println("Interrupted");
            } finally {
                lock.unlock();
            }
        });

        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e){
            e.printStackTrace();
        }

        //打断线程t2的等待
        t2.interrupt();

    }



}
